from tkinter import *
from tkinter import ttk
from tkinter import constants,filedialog
from tkinter import messagebox

import win32clipboard
from urllib import parse
import os

from util.time import *
from util.trans import *
from util.divide_text_by_lines import *

LOG_LINE_NUM = 0
INPUT_FILE_NAME = ""

import zhconv


def hans_2_hant(hans_str: str):
    '''
    Function: 将 hans_str 由简体转化为繁体
    '''
    return zhconv.convert(hans_str, 'zh-hant')

def hant_2_hans(hant_str: str):
    '''
    Function: 将 hant_str 由繁体转化为简体
    '''
    return zhconv.convert(hant_str, 'zh-hans')

#获取当前时间
def get_current_time():
    current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    return current_time

#日志动态打印
def write_log_to_Text(logmsg):
    global LOG_LINE_NUM
    log_data_Text.config(state=NORMAL)
    current_time = get_current_time()
    logmsg_in = str(current_time) +" " + str(logmsg) + "\n"      #换行
    if LOG_LINE_NUM <= 7:
        log_data_Text.insert(END, logmsg_in)
        LOG_LINE_NUM = LOG_LINE_NUM + 1
    else:
        log_data_Text.delete(1.0,2.0)
        log_data_Text.insert(END, logmsg_in)
    log_data_Text.config(state=DISABLED)

def str_trans_hbase():
    src = input_data_Text.get(1.0,END).strip().replace("\n","")
    if src:
        try:
            resultData = strans(src)
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,resultData)
            # write_log_to_Text("INFO: success")
        except:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,"字符串转失败")
    else:
        print("error!")
        # write_log_to_Text("ERROR: failed")


def str_trans_url():
    src = input_data_Text.get(1.0,END).strip().replace("\n","").encode()
    if src:
        try:
            resultData = parse.unquote(strans(src))
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,resultData)
            # write_log_to_Text("INFO: success")
        except:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,"字符串转失败")
    else:
        print("error!")
        # write_log_to_Text("ERROR: failed")

def str_trans_time():
    src = input_data_Text.get(1.0,END).strip()
    if src:
        try:
            resultData = time_trans(src)
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,resultData)
            src_times = src.split("\n")
            out_times = resultData.split("\n")
            for i, src_time in enumerate(src_times):
                write_log_to_Text("INFO: "+src_time+" To: "+out_times[i])
        except:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,"字符串转失败")
    else:
        write_log_to_Text("ERROR: failed") 

def str_get_time():
    time_now = time.time()
    stamp_now = str(int(round(time_now*1000)))
    resultData = "时间戳为：     " + stamp_now + "\n时间格式显示： " + stamp_to_date(stamp_now)
    result_data_Text.delete(1.0,END)
    result_data_Text.insert(1.0,resultData)

def hans2hant():
    src = input_data_Text.get(1.0,END).strip()
    if src:
        try:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,hans_2_hant(src))
        except:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,"字符串转失败")
    else:
        write_log_to_Text("ERROR: failed") 

def hant2hans():
    src = input_data_Text.get(1.0,END).strip()
    if src:
        try:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,hant_2_hans(src))
        except:
            result_data_Text.delete(1.0,END)
            result_data_Text.insert(1.0,"字符串转失败")
    else:
        write_log_to_Text("ERROR: failed") 

def clear_data():
    result_data_Text.delete(1.0,END)
    input_data_Text.delete(1.0,END)


def clear_datalog():
    global LOG_LINE_NUM
    log_data_Text.delete(1.0,END)
    LOG_LINE_NUM = 0

def copyresultdata():
    copystring = result_data_Text.get(1.0,END)[:-1]
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(copystring,win32clipboard.CF_TEXT)
    win32clipboard.CloseClipboard()
    write_log_to_Text("INFO: 复制结果到剪贴板")

def page2selectfile():

    # get filename
    filename = filedialog.askopenfilename(initialdir="C:\\",title="This is title",parent=page2)
    page2_file_path_Text.delete(1.0,END)
    page2_file_path_Text.insert(1.0,filename)

def page2selectpath():
    # get filename
    filename = filedialog.askdirectory(initialdir="C:\\",title="This is title",parent=page2)
    page2_path_Text.delete(1.0,END)
    page2_path_Text.insert(1.0,filename)

def page3selectfile():
    filename = filedialog.askopenfilename(initialdir="C:\\",title="This is title",parent=page2)
    page3_file_path_Text.delete(1.0,END)
    page3_file_path_Text.insert(1.0,filename)

def page3selectpath():
    # get filename
    filename = filedialog.askdirectory(initialdir="C:\\",title="This is title",parent=page2)
    page3_path_Text.delete(1.0,END)
    page3_path_Text.insert(1.0,filename)

trans_model_dic={"hbase转换":0,"url编码转换":1,"简体转繁体":2,"繁体转简体":3}
trans_model_list = list(trans_model_dic.keys())

switch = {
    'hbase转换': strans,
    '简体转繁体': hans_2_hant,
    '繁体转简体': hant_2_hans,
    'url编码转换':strans_url
}

def tran_file():
    global trans_model_dic
    input_file_name = page2_file_path_Text.get(1.0,END)[:-1]
    output_path_name = page2_path_Text.get(1.0,END)[:-1]
    if output_path_name == '' or (not os.path.exists(output_path_name)):
        output_path_name = "D:/"
        msg = get_current_time() + "\t输出路径为空或者不存在，使用默认输出路径：  D:/\n"
        page2logText.insert(END,msg)
    input_file_name_ex = os.path.splitext(os.path.basename(input_file_name))
    print (input_file_name_ex)
    output_file_name = os.path.join(output_path_name,input_file_name_ex[0]+"stran"+input_file_name_ex[1])
    mode = trans_model_list[v.get()]
    print(mode)
    msg = get_current_time() + "\t开始将文件"+input_file_name+"进行"+mode+"，输出至文件"+output_file_name + "\n"
    page2logText.insert(END,msg)
    if os.path.exists(input_file_name) and os.path.isfile(input_file_name) :
        outputFile = open(output_file_name,"w", encoding="utf-8")
        with open(input_file_name, encoding="utf-8") as inputFile:
            i = 0
            line = inputFile.readline()
            while (line):
                output_string = switch.get(mode, strans)(line)
                outputFile.writelines(output_string)
                line = inputFile.readline()
                i = i+1
                if i%1000 == 0:
                    msg = get_current_time() + "\t已经处理"+str(i)+"行数据\n"
                    page2logText.insert(END,msg)
        outputFile.close()
        msg = get_current_time() + "\t转换完成！请查看输出文件："+output_file_name + "\n"
        page2logText.insert(END,msg)

    else:
        error_string = get_current_time() + "\t输入的文件不存在！\n"
        page2logText.insert(END,error_string)

def page3divide():
    input_file = page3_file_path_Text.get(1.0,END)[0:-1]
    output_path = page3_path_Text.get(1.0,END)[0:-1]
    try:
        divide_lines = int(page3_get_small_file_lins_Text.get(1.0,END)[0:-1])
        divide_number = int(page3_get_small_file_number_Text.get(1.0,END)[0:-1])
        if os.path.isfile(input_file) and os.path.isdir(output_path):
            divide_text_by_line(big_file=input_file,small_file_lines=divide_lines,new_file_path=output_path,times=divide_number)
            messagebox.showwarning('消息','转换完成！')
        else:
            messagebox.showwarning('警告','输入文件路径错误或者输出路径错误！')
            print("输入文件路径错误或者输出路径错误！")
    except Exception as errors:
        messagebox.showwarning('警告','请输入数字')
        print(str(errors)) 
    

    
if __name__ == '__main__':
    little_tools = Tk()
    little_tools.title("小工具v1.1")
    little_tools.geometry('1068x681')

    universal_height = 1068
    nb = ttk.Notebook(little_tools)
    # adding Frames as pages for the ttk.Notebook
    # first page, which would get widgets gridded into it
    page1 = ttk.Frame(nb,width = 681,height = universal_height)
    # second page
    page2 = ttk.Frame(nb,width = 681,height = universal_height)
    page3 = ttk.Frame(nb,width = 681,height = universal_height)
    page4 = ttk.Frame(nb,width = 681,height = universal_height)
    page5 = ttk.Frame(nb,width = 681,height = universal_height)
    nb.add(page1, text='输入转换')
    nb.add(page2, text='文档转换')
    nb.add(page3, text='大文件分割')
    nb.add(page4, text='文件格式转换')
    nb.add(page5, text='接口模拟')
    nb.grid()

    # 第一个选项卡
    #标签
    init_data_label = Label(page1, text="待处理数据")
    init_data_label.grid(row=0, column=0)
    result_data_label = Label(page1, text="输出结果")
    result_data_label.grid(row=0, column=12)
    log_label = Label(page1, text="日志")
    log_label.grid(row=12, column=0)
    #文本框
    input_data_Text = Text(page1, width=67, height=35)  #原始数据录入框
    input_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
    result_data_Text = Text(page1, width=70, height=49)  #处理结果展示
    result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
    log_data_Text = Text(page1, width=66, height=9, state = DISABLED)  # 日志框
    log_data_Text.grid(row=13, column=0, columnspan=10)
    #按钮
    page_one_button = Button(page1, text="hbase转换", bg="lightblue", width=10,command=str_trans_hbase)  # 
    page_one_button.grid(row=1, column=11)
    page_one_button = Button(page1, text="url编码转换", bg="lightblue", width=10,command=str_trans_url)  # 
    page_one_button.grid(row=2, column=11)
    page_one_button = Button(page1, text="时间转换", bg="lightblue", width=10,command=str_trans_time)  # 调用内部方法  
    page_one_button.grid(row=3, column=11)
    page_one_button = Button(page1, text="获取当前时间", bg="lightblue", width=10,command=str_get_time)  # 
    page_one_button.grid(row=4, column=11)
    page_one_button = Button(page1, text="简体转繁体", bg="lightblue", width=10,command=hans2hant)  # 调用内部方法  
    page_one_button.grid(row=5, column=11)
    page_one_button = Button(page1, text="繁体转简体", bg="lightblue", width=10,command=hant2hans)  # 调用内部方法  
    page_one_button.grid(row=6, column=11)
    page_one_button = Button(page1, text="清空数据", bg="lightblue", width=10,command=clear_data)  # 调用内部方法  
    page_one_button.grid(row=7, column=11)
    page_one_button = Button(page1, text="复制结果", bg="lightblue", width=10,command=copyresultdata)  # 调用内部方法  
    page_one_button.grid(row=8, column=11)
    page_one_button = Button(page1, text="清空日志", bg="lightblue", width=10,command=clear_datalog)  # 调用内部方法  
    page_one_button.grid(row=12, column=1)

    # 第二个选项卡
    text_width = 130
    Label(page2, text="输入文件").grid(row=0,column=0, sticky=W)
    Label(page2, text="输出路径").grid(row=1,column=0, sticky=W)
    Label(page2, text="转换模式").grid(row=3,column=0, sticky=W)
    Label(page2, text="日志").grid(row=8,column=0, sticky=W+N)
    button_opt = {'fill': constants.BOTH}
    # font_text = tf.Font(family='宋体',size=14)
    page2_file_path_Text = Text(page2,width=text_width, height=1)
    page2_file_path_Text.grid(row=0,column=1)
    Button(page2, text = "文件选择", command = page2selectfile).grid(row = 0, column = 2, sticky=W)
    page2_path_Text = Text(page2,width=text_width, height=1)
    page2_path_Text.grid(row=1,column=1)
    Button(page2, text = "路径选择", command = page2selectpath).grid(row = 1, column = 2, sticky=W)
    # 单选规则
    v = IntVar()
    v.set(1)
    Radiobutton(page2,text ="hbase转换",variable = v,value =0).grid(row=3,column=1, sticky=W)
    Radiobutton(page2,text ="url编码转换",variable = v,value =1).grid(row=4,column=1,  sticky=W)
    Radiobutton(page2,text ="简体转繁体",variable = v,value =2).grid(row=5,column=1,  sticky=W)
    Radiobutton(page2,text ="繁体转简体",variable = v,value =3).grid(row=6,column=1,  sticky=W)
    # 转换按键
    Button(page2, text="开始转换",command=tran_file).grid(row = 3, column = 2,  sticky=W)
    # 输出log框
    page2logText = Text(page2,width=text_width+10, height=30, state = NORMAL)
    page2logText.grid(row=8,column=1,columnspan=2)

    # 第三个选项卡
    Label(page3, text="大文件选择:").grid(row=0,column=0, sticky=E)
    Label(page3, text="输出路径选择:").grid(row=1,column=0, sticky=E)
    Label(page3, text="输出小文件行数:").grid(row=2,column=0, sticky=E)
    Label(page3, text="输出小文件个数:").grid(row=2,column=2, sticky=E)
    page3_file_path_Text = Text(page3,width=text_width, height=1)
    page3_file_path_Text.grid(row=0,column=1,columnspan=4)
    Button(page3, text = "文件选择", command = page3selectfile).grid(row = 0, column = 5, sticky=W)
    page3_path_Text = Text(page3,width=text_width, height=1)
    page3_path_Text.grid(row=1,column=1,columnspan=4)
    page3_get_small_file_lins_Text = Text(page3,width=20,height=1)
    page3_get_small_file_lins_Text.grid(row=2,column=1, sticky=W)
    page3_get_small_file_lins_Text.insert(1.0,1000)
    page3_get_small_file_number_Text = Text(page3,width=20,height=1)
    page3_get_small_file_number_Text.grid(row=2,column=3, sticky=W)
    page3_get_small_file_number_Text.insert(1.0,30)
    Button(page3, text = "路径选择", command = page3selectpath).grid(row = 1, column = 5, sticky=W)
    Button(page3, text = "开始转换", command = page3divide).grid(row = 2, column = 5, sticky=W)

    little_tools.mainloop() 